<!-- Created by henian.xu on 2018/9/4. -->

<template>
    <div 
        class="tree-picker"
        v-clickoutside="handleClose">
        <!--<el-input
            ref="reference"
            :readonly="true"
            height="200px"
            @focus="handleFocus"/>-->
        <div 
            class="inner"
            @click="handleFocus">
            <Tags ref="reference">
                <el-tag
                    v-for="(item) in checkedData"
                    :key="item.id"
                    size="small"
                    disable-transitions
                    type="info">{{ item[props.label] }}</el-tag>
            </Tags>
            <i class="icon el-icon-arrow-down"/>
        </div>
        <transition
            @after-leave="doDestroy"
            name="el-zoom-in-top">
            <el-select-menu
                ref="popper"
                :append-to-body="true"
                v-show="visible"
            >
                <div 
                    v-if="filterable" 
                    class="pa-a">
                    <el-input 
                        placeholder="输入关键字进行过滤" 
                        v-model="filterText"/>
                </div>
                <el-tree
                    ref="tree"
                    :data="treeData"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    highlight-current
                    @check="onTreeCheck"
                    :filter-node-method="onTreeFilterMethod"
                    :props="props"/>
            </el-select-menu>
        </transition>
    </div>
</template>

<script>
import selectMixin from './mixin';
import Tags from './tags';
export default {
    name: 'TreePicker',
    mixins: [selectMixin],
    components: { Tags },
    data() {
        return {
            treeData: [],
            filterText: '',
            loaded: false,
        };
    },
    props: {
        value: {
            type: Array,
            required: true,
        },
        remote: {
            type: String,
            required: true,
        },
        remoteParams: {
            type: Object,
            default() {
                return {};
            },
        },
        selectAnyOne: {
            type: Boolean,
            default: false,
        },
        filterable: {
            type: Boolean,
            default: false,
        },
        props: {
            type: Object,
            default() {
                return {
                    label: 'name',
                    children: 'children',
                };
            },
        },
    },
    computed: {
        checkedData: {
            get() {
                const { value, loaded } = this;
                const { tree } = this.$refs;
                const res = [];
                if (!tree) return res;
                value.forEach(item => {
                    const node = tree.getNode(item);
                    console.log(loaded, value, node);
                    if (node) res.push(node.data);
                });
                return res;
            },
            set(val) {
                const res = val.reduce((prev, curr) => {
                    prev.push(curr.id);
                    return prev;
                }, []);
                this.$emit('input', res);
            },
        },
    },
    watch: {
        value: {
            handler(val) {
                this.setCheckedKeys(val);
            },
        },
        filterText(val) {
            this.$refs.tree.filter(val);
        },
    },
    methods: {
        getDataList() {
            // /sp/shopGoodsCat/selectAll
            this.$http
                .get(this.remote, {
                    ...this.remoteParams,
                    _isRepeat: true,
                })
                .then(json => {
                    const res = json.data;
                    this.treeData = this.$utils.Convert.listToTree(res.data);
                    this.setCheckedKeys(this.value);
                    this.$nextTick(() => {
                        this.loaded = true;
                    });
                });
        },
        setCheckedKeys(val) {
            if (!this.$refs.tree) return;
            this.$refs.tree.setCheckedKeys(val);
        },
        onTreeFilterMethod(value, data) {
            if (!value) return true;
            return data[this.props.label].indexOf(value) !== -1;
        },
        onTreeCheck(data, checkedData) {
            // checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys
            const { checkedNodes } = checkedData;

            if (this.selectAnyOne) {
                let childrenList = [];
                checkedNodes.forEach(item => {
                    const children = item[this.props.children];
                    if (!children || !children.length) return;
                    childrenList = childrenList.concat(
                        children.reduce((prev, curr) => {
                            prev.push(curr.id);
                            return prev;
                        }, []),
                    );
                });
                for (let i = checkedNodes.length, item; (item = checkedNodes[--i]); ) {
                    if (childrenList.indexOf(item.id) === -1) continue;
                    checkedNodes.splice(i, 1);
                }
            } else {
                for (let i = checkedNodes.length, item; (item = checkedNodes[--i]); ) {
                    const children = item[this.props.children];
                    if (!children || !children.length) continue;
                    checkedNodes.splice(i, 1);
                }
            }
            this.checkedData = checkedNodes;
            // console.log(data, checkedData);
        },
    },
    created() {
        this.getDataList();
    },
};
</script>

<style lang="scss">
.tree-picker {
    /*display: inline-block;*/
    /*width: 200px;*/
    /*min-width: 200px;*/
    > .inner {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        border: 1px solid #dcdfe6;
        border-radius: 4px;

        > .tags {
            flex: 1 1 1%;
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: flex-start;
            flex-wrap: wrap;
            padding: $padding-small 0 0 0;
            min-height: 32px;

            > .el-tag {
                margin: 0 $margin-small $margin-small $margin-small;
            }
        }

        &:focus {
            border-color: $color-main;
            outline: none;
        }
        > .icon {
            flex: 0 0 auto;
            width: 30px;
            text-align: center;
            color: #c0c4cc;
        }
    }
}
</style>
